<template>
  <div class="container">
    <h1 style="text-align: center">用户登录</h1>
    <el-form label-position="top">
      <el-form-item label="用户名" :error="state.formError.username">
        <el-input v-model="state.form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" :error="state.formError.password">
        <el-input type="password" v-model="state.form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="doLogin" type="primary">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {userInfoStore} from "@/stores/counter.js";
import {useRouter} from 'vue-router'
import {reactive} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus"

const info = userInfoStore()
const router = useRouter()
const state = reactive({
  form: {
    username: "",
    password: ""
  },
  formError: {
    username: "",
    password: ''
  }
})

function doLogin() {
  state.formError = {}
  _axios.post("/api/login/", state.form).then((res) => {
    if (res.data.code === 0) {
      info.doLogin(res.data.data)
      router.push({name: "home"})
    } else if (res.data.code === 2001) {
      for (let key in res.data.detail) {
        state.formError[key] = res.data.detail[key][0]
      }
    } else {
      ElMessage.error("请求失败")
    }
  })
}

</script>

<style scoped>
.container {
  width: 300px;
  margin: 100px auto;
  padding: 10px 40px;
  border: 1px solid #dddddd;
}
</style>